/**
 * 
 */
package com.taobao.client.buyer;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.VerticalPanel;

import com.taobao.client.BuyerPage;
import com.taobao.client.Data;
import com.taobao.client.RPC;
import com.taobao.client.buyer.custom.CustomButton;
import com.taobao.client.obj.TopItem;
import com.taobao.client.pages.AddOrderMemo;
import com.taobao.client.pages.Bid;
import com.taobao.client.util.PopBox;

/**
 * A vertical panel that displays a list of items that can be bought
 * 
 * @author hujingfei.pt@taobao.com
 * 
 */
public class SellerItemList extends VerticalPanel implements ClickHandler {

	private static final int VISIBLE_ITEM_COUNT = 8;

	private HTML countLabel = new HTML();
	private HTML newerButton = new HTML(
			"<a href='javascript:;'>&lt; newer</a>", true);
	private HTML olderButton = new HTML(
			"<a href='javascript:;'>older &gt;</a>", true);

	private Button doBuyCarButton = new Button("购物车结帐");

	private FlexTable flexTable = new FlexTable();

	private HorizontalPanel navBar = new HorizontalPanel();

	private Data data;
	private int startIndex;
	private List<TopItem> sil;

	private List<CustomButton> buyCarList = new ArrayList<CustomButton>();

	// Default empty constructor
	public SellerItemList() {
		super();

		// Hook up events.
		newerButton.addClickHandler(this);
		olderButton.addClickHandler(this);
	}

	// Getter and setter methods
	public FlexTable getFlexTable() {
		return flexTable;
	}

	public void setFlexTable(FlexTable flexTable) {
		this.flexTable = flexTable;
	}

	// Initializing
	public void initialize(List<TopItem> sil, Data data) {

		doBuyCarButton.addClickHandler(this);

		this.sil = sil;
		this.data = data;
		this.add(doBuyCarButton);
		this.add(flexTable);

		// Create the 'navigation' bar at the upper-right.
		HorizontalPanel innerNavBar = new HorizontalPanel();

		innerNavBar.add(newerButton);
		innerNavBar.add(countLabel);
		innerNavBar.add(olderButton);

		navBar.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		navBar.add(innerNavBar);

		initTable();
		update();
	}

	/**
	 * 事件处理
	 */
	@Override
	public void onClick(ClickEvent arg0) {
		Object sender = arg0.getSource();
		if (sender == olderButton) {
			// Move forward a page.
			startIndex += VISIBLE_ITEM_COUNT;
			if (startIndex >= sil.size()) {
				startIndex -= VISIBLE_ITEM_COUNT;
			} else {
				update();
			}
		} else if (sender == newerButton) {
			// Move back a page.
			startIndex -= VISIBLE_ITEM_COUNT;
			if (startIndex < 0) {
				startIndex = 0;
			} else {
				update();
			}
		} else if (sender == doBuyCarButton) {
			if (buyCarList.size() == 0) {
				PopBox.error("购买出错", "购物车为空");
				return;
			}
			// Clear the old content
			this.clear();
			// Initialize
			this.add(Bid.getBid(this, buyCarList));
		} else if (sender instanceof CustomButton) {
			CustomButton tempB = (CustomButton) sender;

			boolean carBuy2 = tempB.getText().equals(carBuy);
			buyCarList.add(tempB);
			if (carBuy2) {// 购物车直接返回
				AddOrderMemo memo = new AddOrderMemo(tempB);
				memo.show();
				return;
			}

			AddOrderMemo memo = new AddOrderMemo(tempB);
			memo.show();
			
			// Clear the old content
			this.clear();
			// Initialize
			this.add(Bid.getBid(this, buyCarList));
		}
	}

	/**
	 * 添加订单事件,由Bid触发
	 * 
	 * @param iid
	 * @param name
	 * @param phone
	 * @param mobile
	 * @param province
	 * @param city
	 * @param area
	 * @param division_code
	 * @param post_code
	 * @param address_detail
	 * @param isNewAddress
	 */
	public void addTrade(final String iid, String name, String phone,
			String mobile, String province, String city, String area,
			String division_code, String post_code, String address_detail,
			boolean isNewAddress,String memos,String discount) {

		AsyncCallback<String> callback = new AsyncCallback<String>() {
			@Override
			public void onFailure(Throwable arg0) {
				PopBox.error("Buy Items Error:\t", arg0.getLocalizedMessage());
			}

			@Override
			public void onSuccess(String arg0) {
				PopBox.ok("Buy Items Succeed:\t", "item id = " + iid);
				// Update the list of buyer's trades
				RPC.getService().tradeBoughtGet(data.getBuyer(),
						BuyerPage.boughtTradeCallBack);
			}
		};

		List<TopItem> addItems = new ArrayList<TopItem>();
		// find the iid in list
		for (TopItem i : sil) {
			System.out.println("i.iid = " + i.iid);
			if (iid.indexOf(i.iid) >= 0) {
				addItems.add(i);
			}
		}
		RPC.getService().addTrade(addItems, data.getBuyer(), data.getSeller(),
				name, phone, mobile, province, city, area, division_code,
				post_code, address_detail, isNewAddress,memos,discount, callback);
	}

	private void initTable() {
		// Create the header row.
		flexTable.setText(0, 0, "Picture");
		flexTable.setText(0, 1, "Title");
		flexTable.setText(0, 2, "Price");
		flexTable.setText(0, 3, "Quantity");
		flexTable.setWidget(0, 4, navBar);

		// Initialize the rest of the rows.
		for (int i = 0; i < VISIBLE_ITEM_COUNT; ++i) {
			flexTable.setText(i + 1, 0, "");
			flexTable.setText(i + 1, 1, "");
			flexTable.setText(i + 1, 2, "");
			flexTable.setText(i + 1, 3, "");
			flexTable.setText(i + 1, 4, "");
			flexTable.setText(i + 1, 5, "");
		}
	}

	final String carBuy = "购物车";

	private void update() {
		// Update the older/newer buttons & label.
		int count = sil.size();
		int max = startIndex + VISIBLE_ITEM_COUNT;
		if (max > count) {
			max = count;
		}

		newerButton.setVisible(startIndex != 0);
		olderButton.setVisible(startIndex + VISIBLE_ITEM_COUNT < count);
		countLabel
				.setText("" + (startIndex + 1) + " - " + max + " of " + count);

		// Show the selected items.
		int i = 0;
		for (; i < VISIBLE_ITEM_COUNT; ++i) {
			// Don't read past the end.
			if (startIndex + i >= count) {
				break;
			}

			Button buyButton = new CustomButton("Buy");
			buyButton.addClickHandler(this);

			Button buyCarButton = new CustomButton(carBuy);
			buyCarButton.addClickHandler(this);

			TopItem item = sil.get(startIndex + i);
			((CustomButton) buyButton).setIid(item.iid);
			((CustomButton) buyCarButton).setIid(item.iid);

			// Add a new row to the table, then set each of its columns to the
			// item's picture, title, price and quantity.
			Image image = new Image(item.pic);
			image.setSize("30px", "30px");
			flexTable.setWidget(i + 1, 0, image);
			flexTable.setText(i + 1, 1, item.title);
			flexTable.setText(i + 1, 2, item.price);
			flexTable.setText(i + 1, 3, String.valueOf(item.topSku.size()));
			flexTable.setWidget(i + 1, 4, buyButton);
			flexTable.setWidget(i + 1, 5, buyCarButton);
		}

		// Clear any remaining slots.
		for (; i < VISIBLE_ITEM_COUNT; ++i) {
			flexTable.setHTML(i + 1, 0, "&nbsp;");
			flexTable.setHTML(i + 1, 1, "&nbsp;");
			flexTable.setHTML(i + 1, 2, "&nbsp;");
			flexTable.setHTML(i + 1, 3, "&nbsp;");
			flexTable.setHTML(i + 1, 4, "&nbsp;");
		}
	}
}
